package com.xp.basic.heima.nio.netty.simpledemo.chat.handler;

import com.xp.basic.heima.nio.netty.simpledemo.chat.message.LoginResponseMessage;
import com.xp.basic.heima.nio.netty.simpledemo.chat.message.LoginReuqestMessage;
import com.xp.basic.heima.nio.netty.simpledemo.chat.service.UserServiceFactory;
import com.xp.basic.heima.nio.netty.simpledemo.chat.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class LoginReuqestMessageHandler extends SimpleChannelInboundHandler<LoginReuqestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginReuqestMessage msg) throws Exception {
        String username = msg.getUsername();
        String password = msg.getPassword();
        boolean login = UserServiceFactory.getUserService().login(username, password);
        LoginResponseMessage responseMessage;
        if (login) {
            responseMessage = new LoginResponseMessage(true, "login success ");

            //登录成功之后的处理
            SessionFactory.getSession().bind(ctx.channel(), username);

        } else {
            responseMessage = new LoginResponseMessage(false, " username or password error ");
        }

        ctx.writeAndFlush(responseMessage);
    }
}
